package apple.ui.awt;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import apple.core.Apple;

public class AppleII {

   static Logger logger = Logger.getLogger(AppleII.class);

   private static void createAndShowGUI(final Apple apple, Monitor monitor) {

      // JFrame is used to avoid flicker
      final Frame frame = new JFrame(Apple.APPLICATION_TITLE);
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            apple.shutdown();
            frame.dispose();
         }

         public void windowIconified(WindowEvent e) {
            apple.suspend();
         }

         public void windowDeiconified(WindowEvent e) {
            apple.resume();
         }
      });
      frame.add(monitor);

      // Display the window.
      frame.pack();
      frame.setVisible(true);
   }

   /**
    * @param args
    */
   public static void main(String[] args) throws Exception {

      BasicConfigurator.configure();

      final Monitor monitor = new Monitor();
      final Keyboard keyboard = new Keyboard();

      monitor.addKeyListener(keyboard);
      monitor.setFocusTraversalKeysEnabled(false);

      final Apple apple = new Apple("Christiaan's Apple IIe");
      apple.setMonitor(monitor);
      keyboard.setKeyboardDecoder(apple.getKeyboardDecoder());

      // Schedule a job for the event-dispatching thread:
      // creating and showing this application's GUI.
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI(apple, monitor);
            monitor.requestFocusInWindow();
         }
      });

      apple.startup();

      logger.debug(String.format("Thread \"%s\" finished", Thread
            .currentThread().getName()));
   }
}
